/// <reference path="node_modules/@types/chrome/index.d.ts"/>

let changeColor = document.getElementById('changeColor');

chrome.storage.sync.get("color", ({ color }) => {
    changeColor.style.backgroundColor = color;
});

changeColor.addEventListener("click", async () => {
    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); // 获取当前页面标签对象

    console.log('触发标签：', tab.id);

    chrome.scripting.executeScript({
        target: { tabId: tab.id },
        function: setPageBackgroundColor,
    });
});

function setPageBackgroundColor() {
    chrome.storage.sync.get("color", ({ color }) => {
        console.log('设置页面背景色')
        document.body.style.backgroundColor = color;
    });
}

let newTab = document.getElementById('newTab');

newTab.addEventListener("click", async () => {
    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); // 获取当前页面标签对象
    let idx = tab.index + 1;
    chrome.tabs.create({
        url: './panel.html#home',    // https://www.baidu.com
        // index: idx,
        active: false,
    }).then((result) => {
        chrome.scripting.executeScript({
            target: { tabId: tab.id },
            function: () => {
                // console.log(`Hello, tab ${idx} created!`)
                console.log('新增标签页成功！')
            }
        })
    }).catch((error) => {
        chrome.scripting.executeScript({
            target: { tabId: tab.id },
            function: () => {
                console.log(`Sorry, new tab create failed!`)
                console.log('新增标签页失败！')
            }
        })
    })
})

/** @type {HTMLTextAreaElement} */
let consoleText = document.getElementById('consoleText');
let testScript = document.getElementById('testScript');
testScript.addEventListener("click", async () => {
    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    chrome.scripting.executeScript({
        target: { tabId: tab.id, allFrames: true },
        function: () => {
            console.log('注入脚本！')
        }
    }, (injectionResults) => {
        // 测试注入脚本的frame
        consoleText.value = '';
        for (const frameResult of injectionResults) {
            let str = `Iframe ID: ${frameResult.frameId}, Title: ${frameResult.title} \n`;
            consoleText.value += str;
        }

    })
})

let debuggerBtn = document.getElementById('debugger');
debuggerBtn.addEventListener("click", async () => {
    // let bg = chrome.ex     // bg.getResponse();
    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    chrome.scripting.executeScript({
        target: { tabId: tab.id, allFrames: true },
        function: () => {
            console.log('点击了调试按钮！')
        }
    });
    chrome.runtime.sendMessage({ type: "debug" }, (response) => {
        chrome.scripting.executeScript({
            target: { tabId: tab.id, allFrames: true },
            function: (res) => {
                // this 为 window
                if (res != undefined) {
                    console.log(`获取回应！ ${JSON.stringify(res)}`);
                }
                else
                    console.log('信已送达，但没有回音！')
            },
            args: [response]
        });

        chrome.scripting.executeScript({
            target: { tabId: tab.id },
            files: ["./contentScripts/downloadJson.js"]
        })
    })
})

let download = document.getElementById('download');
download.addEventListener("click", async () => {
    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    createFile('[{"A":1}, {"B":2}]')
})

function createFile(str) {
    let blob = new Blob([str], { type: 'application/json' });
    let url = URL.createObjectURL(blob);
    let now = new Date();

    chrome.downloads.download({
        url: url,
        filename: `${now.getTime()}.json`
    })
}